/**
 * WASM 事件系统
 * 提供对 WASM 模块生命周期和事件的监听
 */

/**
 * 事件类型枚举
 */
export enum WasmEventType {
  INITIALIZED = 'initialized',
  ERROR = 'error',
  MESSAGE_RECEIVED = 'messageReceived',
  ACTOR_CREATED = 'actorCreated',
  ACTOR_STOPPED = 'actorStopped',
}

/**
 * 事件监听器类型
 */
export type WasmEventListener = (data?: any) => void;

/**
 * WASM 事件管理器接口
 */
export interface WasmEventManager {
  /**
   * 添加事件监听器
   * @param eventType 事件类型
   * @param listener 监听器函数
   */
  addEventListener(eventType: WasmEventType, listener: WasmEventListener): void;
  
  /**
   * 移除事件监听器
   * @param eventType 事件类型
   * @param listener 监听器函数
   */
  removeEventListener(eventType: WasmEventType, listener: WasmEventListener): void;
  
  /**
   * 触发事件
   * @param eventType 事件类型
   * @param data 事件数据
   */
  dispatchEvent(eventType: WasmEventType, data: any): void;
}

/**
 * WASM 事件管理器实现
 */
export class WasmEventManagerImpl implements WasmEventManager {
  private static instance: WasmEventManagerImpl;
  private eventListeners: Map<WasmEventType, Set<WasmEventListener>> = new Map();
  
  /**
   * 私有构造函数，使用 getInstance 方法获取实例
   */
  private constructor() {
    // 初始化事件监听器映射
    Object.values(WasmEventType).forEach(type => {
      this.eventListeners.set(type as WasmEventType, new Set());
    });
  }
  
  /**
   * 获取 WasmEventManager 单例
   */
  public static getInstance(): WasmEventManagerImpl {
    if (!WasmEventManagerImpl.instance) {
      WasmEventManagerImpl.instance = new WasmEventManagerImpl();
    }
    return WasmEventManagerImpl.instance;
  }
  
  /**
   * 添加事件监听器
   * @param eventType 事件类型
   * @param listener 监听器函数
   */
  public addEventListener(eventType: WasmEventType, listener: WasmEventListener): void {
    const listeners = this.eventListeners.get(eventType);
    if (listeners) {
      listeners.add(listener);
    }
  }
  
  /**
   * 移除事件监听器
   * @param eventType 事件类型
   * @param listener 监听器函数
   */
  public removeEventListener(eventType: WasmEventType, listener: WasmEventListener): void {
    const listeners = this.eventListeners.get(eventType);
    if (listeners) {
      listeners.delete(listener);
    }
  }
  
  /**
   * 触发事件
   * @param eventType 事件类型
   * @param data 事件数据
   */
  public dispatchEvent(eventType: WasmEventType, data: any): void {
    const listeners = this.eventListeners.get(eventType);
    if (listeners) {
      listeners.forEach(listener => {
        try {
          listener(data);
        } catch (error) {
          console.error(`事件监听器错误 (${eventType}):`, error);
        }
      });
    }
  }
}

/**
 * WASM 事件管理器工厂
 */
export class WasmEventManagerFactory {
  /**
   * 获取 WasmEventManager 单例
   */
  public static getInstance(): WasmEventManager {
    return WasmEventManagerImpl.getInstance();
  }
} 